import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faFileAlt } from '@fortawesome/free-solid-svg-icons';
import useKeyHandler from '../hooks/useKeyHandler';
import useContextMenu from '../hooks/useContextMenu';
import { getParentNode } from '../utils/helper';

const FileList = ({ files, editFile, saveFile, deleteFile }) => {
  const [editItem, setEditItem] = useState(false);
  const [value, setValue] = useState('');

  const enterPressed = useKeyHandler(13); // enter
  const escPressed = useKeyHandler(27); // esc

  // 定制一个菜单选项
  const contextMenuTmp = [
    {
      label: '重命名',
      click() {
        let retNode = getParentNode(currentEle.current, 'menu-item');
        setEditItem(retNode.dataset.id);
      }
    },
    {
      label: '删除',
      click() {
        let retNode = getParentNode(currentEle.current, 'menu-item');
        deleteFile(retNode.dataset.id);
      }
    }
  ];

  const currentEle = useContextMenu(contextMenuTmp, '.menu-box');

  // 定义关闭行为
  const closeFn = () => {
    setEditItem('');
    setValue('');
  };

  useEffect(() => {
    const newFile = files.find(file => file.isNew);
    if (newFile && editItem !== newFile.id) {
      // 如果新增一个文件时  又去点击其他文件
      deleteFile(newFile.id);
    }
  }, [editItem]);

  // 新文件创建监听
  useEffect(() => {
    const newFile = files.find(file => file.isNew);
    if (newFile) {
      setEditItem(newFile.id);
      setValue(newFile.title);
    }
  }, [files]);

  // 键盘事件操作
  useEffect(() => {
    if (enterPressed && editItem && value.trim() !== '') {
      const file = files.find(file => file.id === editItem);
      saveFile(editItem, value, file.isNew);
      closeFn();
    }

    if (escPressed && editItem) {
      closeFn();
    }
  });

  return (
    <GroupUl>
      {files.map(file => (
        <li className="list-group-item d-flex align-items-center menu-item" key={file.id} data-id={file.id} data-title={file.title}>
          {file.id !== editItem && !file.isNew && (
            <>
              <span className="mr-2">
                <FontAwesomeIcon icon={faFileAlt} />
              </span>
              <span
                className="col-8"
                onClick={() => {
                  editFile(file.id);
                  closeFn();
                }}
              >
                {file.title}
              </span>
            </>
          )}
          {(file.id === editItem || file.isNew) && <input className="col-9" value={value} onChange={e => setValue(e.target.value)} />}
        </li>
      ))}
    </GroupUl>
  );
};

export default FileList;

// ul 标签
let GroupUl = styled.ul.attrs({
  className: 'list-group list-group-flush menu-box'
})`
  li {
    color: #fff;
    background: none;
  }
`;
